package com.momalib.ning2_nocode.utils;

import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.txt.CharsetDetector;
import org.apache.tika.parser.txt.CharsetMatch;
import org.mozilla.universalchardet.UniversalDetector;
import org.springframework.web.multipart.MultipartFile;
import org.xml.sax.SAXException;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class CommonFileUtil {

    public static File multipartFile2File(MultipartFile multipartFile, String tmpFilePath) throws IOException {
        File convFile = new File(tmpFilePath+"/"+multipartFile.getOriginalFilename());
        multipartFile.transferTo(convFile);
        return convFile;
    }

    public static List<String> getFileFromPath(String filePath) {
        File rootPath = new File(filePath);
        List<File> childFiles = listChild(rootPath);
        List<String> resultList = new ArrayList<>();
        for (File file: childFiles) {
            resultList.add(file.getAbsolutePath());
        }
        return resultList;

    }

    private static List<File> listChild(File file){
        if (!file.exists() || !file.isDirectory()) {
            return new ArrayList<>();
        }
        List<File> resultList = new ArrayList<>();
        File[] fs = file.listFiles();
        if (fs == null) {
            return new ArrayList<>();
        }
        for(File f: fs){
            if(f.isDirectory()) {
                resultList.addAll(listChild(f));
            } else if(f.isFile()) {
                resultList.add(f);
            }
        }
        return resultList;
    }

    public static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            if (input != null) {
                input.close();
            }
            if (output != null) {
                output.close();
            }
        }
    }

    public static Charset fileCharset(String fileName) throws IOException {
        BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
        int p = (bin.read() << 8) + bin.read();
        bin.close();
        Charset code = null;

        switch (p) {
            case 0xefbb:
                code = StandardCharsets.UTF_8;
                break;
            case 0xfffe:
                code = Charset.forName("Unicode");
                // Unicode
                break;
            case 0xfeff:
                code = StandardCharsets.UTF_16BE;
                break;
                //GBK
        }

        return code;
    }

    public static Charset getFileEncoding(File file) {
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis)) { // 确保支持 mark/reset

            Tika tika = new Tika();
            Metadata metadata = new Metadata();

            // 解析文件以提取元数据
            tika.parse(bis, metadata);

            String encoding = metadata.get(Metadata.CONTENT_ENCODING);
            if (encoding != null) {
                return Charset.forName(encoding);
            } else {
                return null;
            }
        } catch (IOException e) {
            System.err.println("Error detecting encoding: " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    public static Charset detectEncoding(File file) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            UniversalDetector detector = new UniversalDetector(null);

            byte[] buf = new byte[4096];
            int nread;
            while ((nread = bis.read(buf)) > 0 && !detector.isDone()) {
                detector.handleData(buf, 0, nread);
            }
            detector.dataEnd();

            String encoding = detector.getDetectedCharset();
            detector.reset();
            return encoding == null ? null : Charset.forName(encoding);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String filePath = "C:\\Users\\Shim\\Documents\\ning2NoCodeSrc\\RuoYi";
        List<String> resultList = getFileFromPath(filePath);
        for (String path: resultList) {
            System.out.println(path);
        }
    }

}
